<?php
/**
 * 菜单管理
 */
namespace App\Services;

use App\Menu;
use App\Role;
use App\User;
use Illuminate\Support\Facades\DB;
use Validator;
use Illuminate\Validation\Rule;

class RolesService
{

    /**
     * 创建｜更新菜单信息
     * @param \Illuminate\Http\Request $request
     * @return array
     * @author: lxy
     * @time: 2020/6/5 9:32 上午
     * @流程:
     */
    public function createOrUpdateRole(\Illuminate\Http\Request $request) {
        $data = $request->all();
        $Rules = [
            'title' => 'required|max:255',
            'power' => 'required'
        ];

        try {
            $validator = Validator::make($data, $Rules);
            if ($validator->fails()) {
                //获取第一条错误信息
                $err = $validator->errors()->all()[0];
                throw new \Exception($err);
            }

            if ($data['id'] > 0) {
                $Role = Role::find($data['id']);
            } else {
                $Role = new Role();
            }

            $Role = $this->RoleBindData($Role,$data);
            $res = $Role->save();
            if (!$res) {
                throw new \Exception('数据库录入失败');
            }

            Menu::CacheUpdate();
            $result = [
                'ok'    => true,
                'msg'   => '操作完成'
            ];

        } catch (\Exception $e) {
            $result = [
                'ok'    => false,
                'msg'   => $e->getMessage()
            ];
        }
        return $result;
    }

    /**
     * 获取管理员｜工作人员信息
     * @author: lxy
     * @time: 2020/6/5 4:46 下午
     * @流程:
     */
    public function GetManageList(){
        $list = DB::table('users')
            ->where('is_staff', 1)
            //->orWhere('is_admin',1)
            ->orderBy('created_at', 'desc')
            ->get()
            ->toArray();

        foreach ($list as &$item){
            $item->role_group = explode(',',$item->role_group);
            array_walk($item->role_group,function (&$key){
                $key =  (int) $key;
            });
        }
         return [
            'ok'    => true,
            'list'  => $list,
        ];
    }


    public function ManageSave(\Illuminate\Http\Request $request) {
        $data = $request->all();
        $Rules = [
            'password' => 'required',
            'name'     => 'required',
            'username' => [
                'required',
                Rule::unique('users')->ignore($data['id']),
            ]
        ];

        if ($data['email']) {
            $Rules['email'] = [
                'required',
                Rule::unique('users')->ignore($data['id']),
            ];
        }

        try {
            $validator = Validator::make($data, $Rules);
            if ($validator->fails()) {
                //获取第一条错误信息
                $err = $validator->errors()->all()[0];
                throw new \Exception($err);
            }

            if ($data['id'] > 0) {
                $User = User::find($data['id']);
            } else {
                $User = new User();
            }

            $User = $this->RoleBindData($User,$data);
            $res = $User->save();
            if (!$res) {
                throw new \Exception('数据库录入失败');
            }
            $result = [
                'ok'    => true,
                'msg'   => '操作完成'
            ];

        } catch (\Exception $e) {
            $result = [
                'ok'    => false,
                'msg'   => $e->getMessage()
            ];
        }
        return $result;
    }




    /**
     * 将请求参数绑定到 Role 对象（用于添加修改）
     * @param object $object
     * @param array $data
     * @return Role
     * @author: lxy
     * @time: 2020/6/4 4:15 下午
     * @流程:
     */
    private function RoleBindData(object $object,array $data) {
        $data = array_filter($data);
        foreach ($data as $key => $val) {
            $object->$key = $val;
        }
        return $object;
    }

}